from tkinter import *
from tkinter import messagebox


def encry(text):
    from cryptography.fernet import Fernet
    textb = bytes(text, encoding="utf8")
    key = b'***'
    f = Fernet(key)
    return f.encrypt(textb)


def pyToMon(app, username, password, website):
    import pymongo
    client = pymongo.MongoClient(host='localhost', port=27017)
    db = client.liujiannan
    collection = db.UserPass
    lst = collection.find({}, {'_id': 0, "ID": 1}).sort('ID', -1)
    newID = int(next(lst)['ID']) + 1
    collection.insert_one({"ID": newID, "app": app, "Username": username
                              , "Password (encrypted)": str(encry(password), encoding='utf-8'), "SiteInfor": website})


def task_input5():
    app = task_txt1.get()
    username = task_txt2.get()
    password = task_txt3.get()
    website = task_txt4.get()
    pyToMon(app, username, password, website)

    task_txt1.delete(0, END)
    task_txt2.delete(0, END)
    task_txt3.delete(0, END)
    task_txt4.delete(0, END)

    messagebox.showinfo('完成', app + "|" + username + "|" + password + "|" + website)


def task_input6():
    messagebox.showinfo('结束', '======Mission_Complete======')
    root.destroy()


def task_input8():
    import pyperclip
    from cryptography.fernet import Fernet
    newpass = str(task_txt7.get())
    newpassb = bytes(newpass, encoding="utf-8")
    key = b'***'
    f = Fernet(key)
    try:
        text = f.decrypt(newpassb)
        pyperclip.copy(str(text, encoding='utf-8'))
        messagebox.showinfo('结束', '===Password is in your clipboard===')
    except:
        messagebox.showinfo('Error', '===Password is not correct===')


root = Tk()
root.title('UserPass')
root.geometry('300x200+500+300')

task_txt1 = Entry(root, width=15, font="微软雅黑")
task_txt1.grid(row=1, column=1)
task1 = Label(root, text='app', width=15, font="微软雅黑")
task1.grid(row=1, column=0)

task_txt2 = Entry(root, width=15, font="微软雅黑")
task_txt2.grid(row=2, column=1)
task2 = Label(root, text='Username', width=15, font="微软雅黑")
task2.grid(row=2, column=0)

task_txt3 = Entry(root, width=15, font="微软雅黑")
task_txt3.grid(row=3, column=1)
task3 = Label(root, text='Password', width=15, font="微软雅黑")
task3.grid(row=3, column=0)

task_txt4 = Entry(root, width=15, font="微软雅黑")
task_txt4.grid(row=4, column=1)
task4 = Label(root, text='Website', width=15, font="微软雅黑")
task4.grid(row=4, column=0)

task5 = Button(root, text="存储", width=15, font="微软雅黑", command=task_input5)
task5.grid(row=5, column=0)

task6 = Button(root, text="离开", width=15, font="微软雅黑", command=task_input6)
task6.grid(row=5, column=1)

task_txt7 = Entry(root, width=15, font="微软雅黑")
task_txt7.grid(row=6, column=1)
task7 = Label(root, text='密码查询', width=15, font="微软雅黑")
task7.grid(row=6, column=0)

task8 = Button(root, text="查询", width=15, font="微软雅黑", command=task_input8)
task8.grid(row=7, column=0, columnspan=2)

root.mainloop()
